package com.wxy.learn.jackson;

import com.wxy.common.exception.BusinessException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * JacksonAccountController
 *
 * @author wxy
 * @since 2023-01-23
 */
@RestController
public class JacksonAccountController {
    /**
     * 创建账号
     *
     * @param accountVo accountVo
     * @return JacksonRsp<AccountVo>
     */
    @PostMapping("/accounts")
    public JacksonRsp<AccountVO> create(@RequestBody AccountVO accountVo) {
        JacksonRsp<AccountVO> jacksonRsp = new JacksonRsp<>();
        try {
            jacksonRsp.setResult(createAccount(accountVo, true));
        } catch (Exception e) {
            jacksonRsp.setCode("CreateAccountError");
            jacksonRsp.setMessage(e.getMessage());
        }

        return jacksonRsp;
    }

    /**
     * 创建账号
     *
     * @param accountVo 账号实体
     * @param flag      是否正常执行
     * @return AccountVo
     */
    private AccountVO createAccount(AccountVO accountVo, boolean flag) {
        if (flag) {
            // 创建账号成功
            accountVo.setCreateTime(LocalDateTime.now());
            return accountVo;
        } else {
            // 创建失败 抛出异常
            throw new BusinessException("create account error");
        }
    }
}